﻿#region License
/*
Copyright (c) 2005-2008, CellAO Team

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the CellAO Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Usings...
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Net;
using System.Reflection;
using AO.Core;
using AO.Core.Config;
using Cell.Core;
using ULPSS;
#endregion
   
namespace LoginEngine
{
    class Program
    {
        static void Main(string[] args)
        {
            
            #region Console Texts...
            string assversion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            Console.Title = "CellAO LoginServer Console. Version: RollerRat - " + assversion.ToString();
            Console.WriteLine("========================================================");
            Console.WriteLine("CellAO copyright 2008 by the CellAO Dev team");
            Console.WriteLine("We are using BSD Licensing for our Core files");
            Console.WriteLine("Cell Framework is copyright under GPL");
            Console.WriteLine("Anarchy Online is copyright by Funcom");
            Console.WriteLine("Thank you for choosing CellAO");
            Console.WriteLine("========================================================");
            Console.WriteLine("Loading LoginEngine...");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[OK]");
            Console.ResetColor();
            #endregion
            Server LoginServer = new Server();
            LoginServer.EnableTCP = true;
            LoginServer.EnableUDP = false;
			// START ULPSS
			try
        {
            Console.WriteLine("......");
            NativeMethods.puts("...... ");
            NativeMethods._flushall();
            Console.WriteLine("......");
        }
        catch (SecurityException)
        {
            Console.WriteLine("TRAP");
        }
    }
			try { LoginServer.TcpIP = IPAddress.Parse(ConfigReadWrite.GetConfig().ListenIP); }
			catch { Console.WriteLine("Error parsing my ip address. Check config file!"); Console.ReadKey(); return; }

            LoginServer.TcpPort = Convert.ToInt32(ConfigReadWrite.GetConfig().LoginPort);
            LoginServer.MaximumPendingConnections = 100;
            string consoleCommand;
            Console.WriteLine("Enter \"start\" to start server, \"stop\" to stop it, \"Adduser\" <Username> <Password> <Characters Allowed> <Expansion> and \"exit\" to exit program");
            while (true)
            {
                consoleCommand = Console.ReadLine();
                switch (consoleCommand.ToLower())
                {
                    case "start":
                        ThreadMgr.Start();
                        LoginServer.Start();
                        break;
                    case "stop":
                        ThreadMgr.Stop();
                        LoginServer.Stop();
                        break;
                    case "exit":
                        Process.GetCurrentProcess().Kill();
                        break;
                    default:
						if (consoleCommand.ToLower().StartsWith("adduser"))
						{
							string[] parts = consoleCommand.Split(' ');
							if (parts.Length < 5)
							{
								Console.WriteLine("Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion>");
								break;
							}
							string username = parts[1];
							string password = parts[2];
							int numChars = 0;
							try
							{
								numChars = int.Parse(parts[3]);
							}
							catch { Console.WriteLine("Error: <number of characters> must be a number (duh!)"); break; }
							int expansions = 0;
							try
							{
								expansions = int.Parse(parts[4]);
                                if (expansions < 0 || expansions > 127)
									throw new Exception();
							}
                            catch { Console.WriteLine("Error: <expansions> must be a number between 0 and 3!"); break; }
							string formatString;
                            formatString = "INSERT INTO `login` (`Flags`,`AccountFlags`,`Username`,`Password`,`Allowed_Characters`,`Expansions`) VALUES('0', '0', '{0}', '{1}', {2}, {3});";

                            LoginEncryption le = new LoginEncryption();

                            string hashedPassword = le.GeneratePasswordHash(password);

							string sql =
								String.Format(formatString,
								username, hashedPassword, numChars, expansions);
							AO.Core.MySqlWrapper wrp = new AO.Core.MySqlWrapper();
							try
							{
								wrp.MySqlInsert(sql);
							}
							catch (MySql.Data.MySqlClient.MySqlException ex)
							{
								switch (ex.Number)
								{
									case 1062: //duplicate entry for key
										Console.WriteLine("A user account with this username already exists.");
										break;
									default:
										Console.WriteLine("An error occured while trying to add a new user account:\n{0}", ex.Message);
										break;
								}
								break;
							}
							Console.WriteLine("User added successfully.");
							break;
						}
                        Console.WriteLine("Unknown command\n");
                        Console.WriteLine("Available commands:");
                        Console.WriteLine("----------------------");
                        Console.WriteLine("start - Starts server.");
                        Console.WriteLine("stop  - Stops server.");
                        Console.WriteLine("adduser  - Adduser <username> <password> <number of characters> <expansion>.");
                        Console.WriteLine("exit  - Exits program.");
                        Console.WriteLine("----------------------\n");
                        break;
                }
            }
        }
    }
}